define('controllers/sp_validForm', function (require, exports, module) {
	"use strict";

	var fnGlobalUrl = require[require.toUrl ? 'toUrl' : 'resolve'];
	var $window = $(window),
		$document = $(document);
	  require('jquery.validform');
    require('jquery.plupload');
		// require('jquery.select2');
	 //  var LayerTitle = require('layer_popup');


	/* ************************************************************ */
	var m_ValidForm = { /* 定义一个首页对象 */
		createNew: function () {
			if (!(window.basePage) || typeof (window.basePage.createNew) !== 'function') {
				window.basePage = {};
				window.basePage.createNew = function () {
					return {};
				}
			}
			var $internal = window.basePage.createNew();
			/* code here for example */
			$internal.validform = null;

			$internal.init = function () { /* 页面类的初始化， 向$internal上绑定功能对象， 如下绑定 Banner 对象 */
				/*code here 如下： */
				this.validform = new $validform();
			};
			/*=================================表单验证 pass==================================*/
			var $validform = new Class({ /* 创建banner对象 */
				initialize: function () {
					this._init();
				}
			});
			$validform.extend({ /* 向banner对象添加 banner的方法  */
				_init: function () {
					this.isAppear = false; /* 是否呈现完毕标志 */
					this.mySwiper = null;
					this.myTimers = undefined; /* 预定义定时器  */
					this._initDom(); /* 获取dom为后续做准备  */
				},
				_initDom: function () { //获取要使用的banner的dom 如下： 
					//var _this = this;
					//_this.sectionNode = $('#J_banner_sect');
				},
				/*=================================表单验证==================================*/
				Valid: function (form) {
          var _this = this;
          if(($('.ie8').length>0)&&($('.J_msg').length>0)){
            $(form).find('[placeholder]').each(function(){
              var _the = $(this),
                  placeholder = _the.attr('placeholder');
              _the.val(placeholder);
              _the.focus(function(){
                $(this).select();
              });
              _the.blur(function(){
                if($(this).val()==''){
                  _the.val(placeholder);
                }
              });
            });
          }
					var _theValid = $(form).Validform({
						tiptype: 3,
						ignoreHidden: false,
						dragonfly: false,
						tipSweep: false,
						label: ".label",
						showAllError: true,
						postonce: true,
						ajaxPost: true,
						datatype: {
							"price": /^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/, // 价格
							"f-phone": /^0\d{2,3}-[1-9]\d{6,7}$/, // 固定电话
							"paw": /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/, // 密码
							"*6-20": /^[^\s]{6,20}$/,
							"z2-4": /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,4}$/,
							"license": /^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$/,
							"phone": /(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/,
							"identity": /^[1-9]([0-9]{14}|[0-9]{17})$/,
						},
						beforeCheck: function (curform) {
							//在验证成功后，表单提交前执行的函数，curform参数是当前表单对象。
							//这里明确return false的话表单将不会提交;
						  return false;
						}
					});
          if($('#J_imgwraper').length>0){
            _this.UploadPictures();
          }
          if($('.J_del_list').length>0){
            _this.deleteItem();
          }          /*==文本域字数限制==*/
          $(form).on('input','.J_txtA',function(){
            var _text = $(this).val().length,
                _onNum = _text,
                _theNum = $(form).find('.J_num'),
                _theHtml = '';
            if (_onNum < 801) {
              _theHtml = _onNum + '/800';
              _theNum.html(_theHtml);
            }else{
              LayerTitle.myLayer({
						  	type: 1,// 1为失败类、2为等待类、3为警示类、不设置时为 0 没有图标
						  	txt: '字数不能超过800个！请修改',// 提示文字，默认为数据出错
              });
              _theHtml = _onNum + '/800';
              _theNum.html(_theHtml);
            }
          });

          $(form).on('click','.J_submit',function(){
            if(($('.ie8').length>0)&&($('.J_msg').length>0)){
              $(form).find('[placeholder]').each(function(){
                var _the = $(this),
                    placeholder = _the.attr('placeholder');
                if(_the.val().indexOf(_the.attr('placeholder'))>-1){

                };
                _the.val(placeholder);
              });
            }            
            if(_theValid.check()){
              if($('.J_xieyi').length>0&&!($('.J_xieyi').is(':checked'))){
                layer.msg($('.J_xieyi').attr('nullmsg'));
                return false;
              }
              _this.submitForm(form);
            }else{
              var text = $(form).find('.Validform_wrong:eq(0)').text();
              layer.msg(text);
            };
          });
          _this.mobilePhone(60);
          _this.changeCode();
				},
        deleteItem: function(){
          var _this = this,
              flag = 0;
          $('.J_del_list').on('ifChanged','.J_all',function(){
            var _the = $(this);
            if(_the.is(':checked')){
              $('.J_item').iCheck('check');
            }else{
              $('.J_item').iCheck('uncheck');
            }

          });
          $('.J_form').on('click','.J_itemDel', function(){
            var _the = $(this),
                _theForm = $('.J_form'),
                _token = _theForm.attr('_token')||'',
                param = _theForm.attr('param')||'',
                submitUrl = _theForm.attr('ajaxUrl')||'',
                value = {id:_the.parents('tr').attr('data-id')},
                content = '';
            if(_the.text()=="取消报名"){
              content = '<div class="pop-box"><div class="abolish"><span></span><p>是否要取消该次报名？</p></div></div>';
            }else{
              content = '<div class="pop-box"><div class="abolish"><span></span><p>是否要删除该条消息？</p></div></div>';
            }
            if(!flag){
              layer.open({
                title: false,
                content: content,
                btn: ['确认','取消'],
                area: ['450px', '280px'],
                yes: function(){
                  flag = 1;
                  layer.load("2",{shade:[.2,"#666"]});
                  $.ajax({
                    type: "POST",
                    url: submitUrl,
                    data: {
                      _token: _token,
                      param: param,
                      data: value
                    },
                  })
                  .done(function (res) {
                    res = eval(res);
                    if(res.code==200){
                      layer.msg(res.msg);
                      for(var i=0;i<value.length;i++){
                        _the.remove();
                      }
                    }else{
                      layer.msg(res.msg);
                    }
                  })
                  .fail(function () {
                    layerText = '网络错误';
                    layer.msg(layerText);
                  })
                  .complete(function(){
                    layer.closeAll();
                    flag = 0;                    
                  });
                }
              })
            }
          });
          $('body').on('click','.J_delete', function(){
            var jud = 1,
                _theForm = $('.J_form'),
                _token = _theForm.attr('_token')||'',
                param = _theForm.attr('param')||'',
                submitUrl = _theForm.attr('ajaxUrl')||'',
                value = [],
                content = '';
            $('.J_item').each(function(index){
              if($(this).is(':checked')){
                var _theId = $(this).parents('tr').attr('data-id');
                value.push({id:_theId});
                jud = 0;
              }
            });
            if($('.J_itemDel:eq(0)').text()=="取消报名"){
              content = '<div class="pop-box"><div class="abolish"><span></span><p>是否要取消该次报名？</p></div></div>';
            }else{
              content = '<div class="pop-box"><div class="abolish"><span></span><p>是否要删除该条消息？</p></div></div>';
            }
            if(!jud&&!flag){
              layer.open({
                title: false,
                content: content,
                btn: ['确认','取消'],
                area: ['450px', '280px'],
                yes: function(){
                  flag = 1;
                  layer.load("2",{shade:[.2,"#666"]});
                  $.ajax({
                    type: "POST",
                    url: submitUrl,
                    data: {
                      _token: _token,
                      param: param,
                      data: value
                    },
                  })
                  .done(function (res) {
                    // res = eval(res);
                    if(res.code==200){
                      layer.msg(res.msg);
                      for(var i=0;i<value.length;i++){
                        $('[data-id="' + value[i].id + '"]').remove();
                      }
                    }else{
                      layer.msg(res.msg);
                    }
                  })
                  .fail(function () {
                    layerText = '网络错误';
                    layer.msg(layerText);
                  })
                  .complete(function(){
                    layer.closeAll();
                    flag = 0;                    
                  });
                }
              });
            }
          });
        },
        submitForm: function(form){
          var _this = this,
              flag = 0;
          if(!flag){
            flag = 1;
            var _theForm = $(form),
                _token = _theForm.attr('_token')||'',
                param = _theForm.attr('param')||'',
                submitUrl = _theForm.attr('ajaxUrl')||'',
                value = _theForm.serializeArray();
            layer.load("2",{shade:[.2,"#666"]});
            $.ajax({
              type: "POST",
              url: submitUrl,
              data: {
                _token: _token,
                param: param,
                data: value
              },
            })
            .done(function (res) {
              layer.closeAll("loading");
              res = eval(res);
              if(res.code==200){
								layer.closeAll();
                layer.msg(res.msg);
                if (res.url||(res.data&&res.data.url)) {
                  var _theUrl = res.url||res.data.url;
                  if(_theUrl==1||_theUrl=='1'){
                    location.reload();
                  }else{
                    setTimeout('window.location.replace("'+_theUrl+'")',2000); 
                  }
                }
              }else{
                layer.msg(res.msg);
              }
              flag = 0;
            })
            .fail(function () {
              layer.closeAll();
              var layerText = '网络错误';
              laye.msg(layerText);
              flag = 0;
            });
          }
        },
        /*=================================图片上传==================================*/
        UploadPictures: function(){ /* 呈现相关逻辑  如swiper 的配置和和绑定等 */
          function UploaderFilObj(userOpts){
            var defOpts = { //实例化一个plupload上传对象
              browse_button : 'J_uploaderbtn',
              url : 'upload.php',
              flash_swf_url : $app.frontJs + 'library/jquery_plugins/plupload/Moxie.swf',
              silverlight_xap_url : $app.frontJs + 'library/jquery_plugins/plupload/Moxie.xap',
              prevent_duplicates : true,//不允许选取重复文件
              max_file_size:10*1024+'kb',//允许上传的最大文件size
              multi_selection: false,//是否多选
              filters: {
                mime_types : [{ //只允许上传图片文件 
                    extensions : "jpg,jpeg,png",//允许上传的图片类型 
                  }]
              },
            }
            var opts = $.extend({},defOpts,userOpts);
            var uploader = new plupload.Uploader(opts);
            //绑定文件添加进队列事件
            uploader.bind('FilesAdded',function(uploader,files){
              if(opts.multi_selection){
                for(var i = 0, len = files.length; i<len; i++){
                  var file_name = files[i].name; //文件名
                  !function(i){
                    previewImage(files[i],function(imgsrc){
                      $(opts.imageContainer).append('<li class="item"><img id="' + opts.imgId + '" src="' + imgsrc + '"/><input type="hidden" value = "'+ imgsrc +'" name="'+ opts.filesUpName + i +'" /></li>');
                    })
                  }(i);
                }
              }else{
                previewImage(files[0],function(imgsrc){
                  $(opts.imageContainer).find(opts.imgId).attr('src',imgsrc);
                  if ($(opts.imageContainer).find('input[type="hidden"]')) {
                    $(opts.imageContainer).find('input[type="hidden"]').val(imgsrc).attr('name',opts.filesUpName);
                  }else{
                    $(opts.imageContainer).append('<input type="hidden" value = "'+ imgsrc +'" name="'+ opts.filesUpName +'" />');
                  }
                })
              }
            });
            //plupload中为我们提供了mOxie对象
            //有关mOxie的介绍和说明请看：https://github.com/moxiecode/moxie/wiki/API
            //如果你不想了解那么多的话，那就照抄本示例的代码来得到预览的图片吧
            function previewImage(file,callback){//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
              if(!file || !/image\//.test(file.type)) return; //确保文件是图片
              if(file.type=='image/gif'){//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
                var fr = new mOxie.FileReader();
                fr.onload = function(){
                  callback(fr.result);
                  fr.destroy();
                  fr = null;
                }
                fr.readAsDataURL(file.getSource());
              }else{
                var preloader = new mOxie.Image();
                preloader.onload = function() {
                  preloader.downsize( 360, 360 );//先压缩一下要预览的图片,宽300，高300
                  var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
                  callback && callback(imgsrc); //callback传入的参数为预览图片的url
                  preloader.destroy();
                  preloader = null;
                };
                preloader.load( file.getSource() );
              } 
            }
            uploader.init(); //初始化  
          }
          UploaderFilObj({
            browse_button : 'J_uploaderbtn',//选择图片的按钮id
            imageContainer: '#J_imgwraper',//上传的外边层class或者id
            imgId: '#J_prev_img',//图片选择后要显示的img标签的id或者class
            filesUpName: $('#J_uploaderbtn').attr('data-name'),//隐藏域的图片上传的name,上传图片时程序用
            multi_selection: false,//是否多选
          });
        },
        /*=================================验证码获取================================*/
        mobilePhone: function(time){
          var _this = this,
              flag = 1,
              seconds = time; //倒计时时长，单位秒
          $('.J_form').on('click','.J_send_btn', function () {
            var codeBtn = $(this),
                codeUrl = codeBtn.attr('data-codeUrl'),
                codeBtnId = codeBtn.attr('data-sendNum'),
                codeType = codeBtn.attr('data-codeType'),
              codeBtnColor = codeBtn.css('background-color'),
              codeBtnBColor = codeBtn.css('border-color'),
              codeBtnTxt = codeBtn.text(),
              inptxt = $('[datatype="m"],[datatype="e"]'),
              codeTxt = inptxt.val(),
              _theType = inptxt.attr('datatype');
            var emil = eval(/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/),
                phoen = eval(/(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/);
            if(emil.test(codeTxt)){
              // codeTxt = {emil:codeTxt};
            }else if(phoen.test(codeTxt)){
              // codeTxt = {tel:codeTxt};
            }else{
              layer.closeAll('loading');
              layer.msg('填写错误无法发送验证码！');
              return;
            }
            if (flag) {
              flag = 0;
              _this.sendValideCode(codeTxt,codeUrl,codeType);// 请求事件
              layer.load('2',{shade: [0.2,'#666']});
              var timer = setInterval(function () {
                if (seconds > 0) {
                  codeBtn.css({
                    'background-color': '#d0d0d0',
                    'border-color': '#d0d0d0',
                    'cursor': 'not-allowed'
                  });
                  codeBtn.attr("disabled", true).text('重发验证码(' + seconds + 's)');
                  seconds--;
                } else {
                  codeBtn.css({
                    'background-color': codeBtnColor,
                    'border-color': codeBtnBColor,
                    'cursor': 'pointer'
                  });
                  codeBtn.attr("disabled", false).text(codeBtnTxt);
                  seconds = time;
                  clearInterval(timer);
                  flag = 1;
                }
              }, 1000);
            }
          });
        },
        sendValideCode: function(tel,codeUrl,type){
          var data = {};
          data.mobile = tel;
          data.send_type = type;
          layer.load("2",{shade:[.2,"#666"]});
          $.ajax({
            url: codeUrl,
            type: 'POST',
            data: data
          })
          .done(function(res){
            layer.closeAll('loading');
            res = eval(res);
            if (res.code == 200) {
              layer.msg('验证码已发送!');
            } else {
              layer.msg(res.msg);
            }
          })
          .fail(function(res){
            layer.closeAll('loading');
            layer.msg('网络错误，发送失败!');
          });
        },
        changeCode: function(){
          var codeImg = $('.J_pos_code').find('img'),
              codeUrl = codeImg.attr('src');
          $('.J_another').on('click',function(){
            codeImg.attr('src',codeUrl + '?' + Date.parse(new Date()) );
          });
        },
				/*=================================表单美化==================================*/
				formBeautify: function(form){
					if ($('.J_sel').length > 0) {
	    			$(form).find('.J_sel').select2({
	    				minimumResultsForSearch:Infinity
	    			});
	    		}
					if ($('.J_downselplugin').length > 0) {
				  	$(form).find('.J_downselplugin').Downselect();
					}
				},
			});
			return $internal; //返回对象
		}
	};
	exports.formValid = function (index) {
		var _theValidForm = m_ValidForm.createNew(); /* 定义首页页面类 */
		_theValidForm.init(); /* 调用首页页面类入口方法  */
		_theValidForm.validform.Valid(index); /* 当dom 加载完成后调用 banner 的呈现函数 */

	};
	exports.formBeautify = function (index) {
		var _theValidForm = m_ValidForm.createNew(); /* 定义首页页面类 */
		_theValidForm.init(); /* 调用首页页面类入口方法  */
		_theValidForm.validform.formBeautify(index); /* 当dom 加载完成后调用 banner 的呈现函数 */
	};
});
